<?php
namespace backend\controllers;

use Yii;
use backend\models\Baseconfigs;
use backend\models\Baselogger;
use backend\models\Basemaster;
use backend\models\PlayerTbl;
use common\service\PubService;
use common\service\ValidateCodeService;
use common\service\WxService;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Cookie;

/**
 * Site controller
 */
class SiteController extends CommonController
{

    const SUCCESS = 200;
    const FAIL = 300;
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error','get-captcha', 'wxlogin'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index', 'error'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['get'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }


    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        //登录页配置网站信息
        $config = Baseconfigs::getConfig();
        $model = new Basemaster();
        $userid = Yii::$app->user->getId();
        $nowTime = date('Y-m-d H:i:s', time());

        if (yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $username = $data['username'];
            $password = $data['userpass'];
            $usercode = strtolower($data['usercode']);
            $checkcode = strtolower(yii::$app->session->get('usercode'));
            $user = Basemaster::findByUsername($username);
            $password = strtolower(md5($password));
            if (empty($user)){
                return $this->renderJson(['retcode' => self::FAIL, 'retmsg'=> '登录失败，登录账号错误']);
            }
            if ($password != strtolower($user->LoginPass)){
                return $this->renderJson(['retcode' => self::FAIL, 'retmsg'=> '登录失败，登录密码错误']);
            }
            if ($usercode != $checkcode){
                return $this->renderJson(['retcode' => self::FAIL, 'retmsg'=> '登录失败，验证码错误']);
            }
            if ($user->UserState){
                return $this->renderJson(['retcode' => self::FAIL, 'retmsg'=> '登录失败，账号已停用']);
            }
            $data['Basemaster']['UserName'] = $username;
            $data['Basemaster']['UserPass'] = $password;
            $data['Basemaster']['LoginPass'] = $password;
            if ($model->load($data) && $model->login()) {
                $this->setLoginFlag();
                //更新登录的时间和本机ip
                $loginDate = $nowTime;
                $loginIP= PubService::real_ip();
                yii::$app->db->createCommand()->update('basemaster',['LoginDate' => $loginDate, 'LoginIP' => $loginIP],'MasterId='.Yii::$app->user->getId())->execute();
                //写入log日志
                $log = new Baselogger();
                $log->LogType = 0;
                $log->LogLogic = '账号登录';
                $log->LogDescribe = '登录成功';
                $log->LogURL = 'http://'.yii::$app->request->serverName.yii::$app->request->url;
                $log->LogDate = $nowTime;
                $log->LogIP = $loginIP;
                $log->MasterId = Yii::$app->user->getId();
                if ($log->save()){
                    return $this->renderJson(['retcode' => self::SUCCESS, 'retmsg'=> '账号登录成功，正在跳转...']);
                }else{
                    return $this->renderJson(['retcode' => self::FAIL, 'retmsg'=> '网络异常，请稍后再试']);
                }
                return $this->renderJson(['retcode' => self::SUCCESS, 'retmsg'=> '账号登录成功，正在跳转...']);
            }
            return $this->renderJson(['retcode' => self::FAIL, 'retmsg'=> '网络异常，请稍后再试']);
        }else{
            yii::$app->user->logout();
            if (!empty($userid)){
                $this->redirect('/');
            }
            return $this->renderPartial('login', [
                'model' => $model,
                'config' => $config,
            ]);
        }
    }


    public function actionWxlogin()
    {
        //微信端进入 通过UnionID获取代理玩家的playerid
        $is_wx = PubService::isWeChat();
        if ($is_wx){
            $wechat = new WxService();
            $redirect_url = yii::$app->params['staticUrl'].'/site/wxlogin';
            $redirect_url = urlencode($redirect_url);
            $info = $wechat->get_user_info($redirect_url);
            $accId = $info['unionid'];
            $playtbl = PlayerTbl::findOne(['AccID'=>$accId]);
            if ($playtbl){
                $playerId = $playtbl->PlayerID;
                $username = 'DL'.$playerId;
                $master = Basemaster::findOne(['UserName'=>$username]);
                if ($master){
                    $model = new Basemaster();
                    $data['Basemaster']['UserName'] = $username;
                    $data['Basemaster']['UserPass'] = $master->UserPass;
                    $data['Basemaster']['LoginPass'] = $master->LoginPass;
                    if ($model->load($data) && $model->login()) {
                        $this->setLoginFlag();
                    }
                }
                $this->redirect('/');
            }
            $this->redirect('/');
        }else{
            $this->redirect('/');
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();
        yii::$app->session->destroy();
        return $this->goHome();
    }


    public function actionGetCaptcha()
    {
        $validataService = new ValidateCodeService();
        $validataService->doimg();
        yii::$app->session->set('usercode', $validataService->getCode());
        yii::$app->end();
    }


    /**
     * 设置登陆标志
     */
    public function setLoginFlag()
    {
        $cache = Yii::$app->cache;
        $loginFlag = "loginFlag_" . Yii::$app->user->getId();
        $time = time() . rand(1, 1000);
        $cache->set($loginFlag, $time, 3600 * 15 * 24);
        $cookies = Yii::$app->response->cookies;
        $cookies->add(new Cookie([
            'name' => $loginFlag,
            'value' => $time,
            'expire'=> time()+3600 * 24 * 365

        ]));
    }


    public function actionError()
    {
        $this->layout = false;
        return $this->renderPartial('error');
    }
}
